﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CommonHelper
{
    public static class SingleCase
    {
        private static Dictionary<Type, object> Type2Instance = new Dictionary<Type, object>();

        /// <summary>
        /// 获取单例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Single<T>()
        {
            var type = typeof(T);
            if (!Type2Instance.ContainsKey(type)) lock (Type2Instance) if (!Type2Instance.ContainsKey(type))
                        Type2Instance[type] = type.Assembly.CreateInstance(type.FullName);

            return (T)Type2Instance[type];
        }

        /// <summary>
        /// 注册类型实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance"></param>
        public static void RegisterSingle<T>(T instance)
        {
            var type = typeof(T);

            lock (Type2Instance)
                Type2Instance[type] = instance;
        }
    }
}
